<?php
namespace app\common\service;

use app\common\model\UserRole as UserRoleModel;
use app\common\validate\UserRoleValidate;

class UserRole{


    public function getRoles(){
        $userRoleModel = new UserRoleModel();

        $roles = $userRoleModel->order('id desc')->paginate(20);

        return $roles;
    }

    /**
     * @param $roleId
     * @return array|mixed
     */
    public function getPermissionByRole($roleId){
        if(!$roleId) {
            return [];
        }

        $role = UserRoleModel::get(['id'=>$roleId]);
        $permission = $role['permission'];
        $permission = unserialize($permission);

        return $permission;
    }


    public function insert($data){

        $userRoleModel = new UserRoleModel();
        $result = $userRoleModel->validate("UserRoleValidate.add")->save($data);

        if(false === $result){
            return ['state'=>0,'message'=>$userRoleModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$userRoleModel->id];
    }


    public function update($data){
        $userRole = new UserRoleModel();

        if(intval($data['id']) <1){
            return ['state'=>0,'message'=>"参数错误"];
        }

        $result = $userRole->validate('UserRoleValidate.edit')->save($data,['id'=>intval($data['id'])]);

        if(false === $result){
            return ['state'=>0,'message'=>$userRole->getError()];
        }

        return ['state'=>1,'message'=>''];
    }

    public function getRole($id){

        $role =  UserRoleModel::get($id);

        $role['permission'] = unserialize($role['permission']);

        if(!$role['permission']) $role['permission'] = [];

        return $role;
    }

    public function delete($ids){

        $userRoleModel = new UserRoleModel();

        $count = $userRoleModel ->destroy($ids);

        return $count;
    }
}